package com.resource.manager.util;

import lombok.SneakyThrows;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class SwingUtil {

    public static int getFontWidth(Graphics g,Font font ,String text){
        if(g == null){
            return 10 * text.length();
        }
        FontMetrics metrics = g.getFontMetrics(font);
        return metrics.stringWidth(text);
    }

    @SneakyThrows
    public static void setTitleIco(Window window){
        BufferedImage image = ImageIO.read(SwingUtil.class.getClassLoader().getResourceAsStream("img/logo.png"));
        window.setIconImage(image);
    }

    public static BufferedImage compressInMemory(BufferedImage srcImage) throws IOException {
        // 初始压缩参数
        float quality = 0.7f;
        int maxAttempts = 10;
        int targetKB = 100;

        // 尺寸缩小（保持宽高比）
        int origWidth = srcImage.getWidth();
        int origHeight = srcImage.getHeight();
        if(origWidth < 200){
            return srcImage;
        }

        int newWidth = Math.min(origWidth, 200);
        int newHeight = (int)(origHeight * ((double)newWidth / origWidth));

        // 创建临时缩放图像
        BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = scaledImage.createGraphics();
        g.drawImage(srcImage, 0, 0, newWidth, newHeight, null);
        g.dispose();

        // 动态质量调整
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

        for (int i = 0; i < maxAttempts; i++) {
            baos.reset();
            param.setCompressionQuality(quality);

            try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
                writer.setOutput(ios);
                writer.write(null, new IIOImage(scaledImage, null, null), param);
            }

            if (baos.size() <= targetKB * 1024) {
                break;
            }
            quality = Math.max(0.1f, quality - 0.1f);
        }

        // 转换回BufferedImage
        byte[] compressedData = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(compressedData);
        return ImageIO.read(bais);
    }
}
